class Solution
{
    int tmp[50010];
public:
    int reversePairs(vector<int>& nums)
    {
        return merge(nums, 0, nums.size() - 1);
    }

    int merge(vector<int>& nums, int left, int right)
    {
        if (left >= right) return 0;
        int ret = 0;

        int mid = (left + right) >> 1;

        ret += merge(nums, left, mid);
        ret += merge(nums, mid + 1, right);

        int cur1 = left, cur2 = mid + 1, i = 0;
        while (cur1 <= mid && cur2 <= right)
        {
            if (nums[cur1] <= nums[cur2])
            {
                tmp[i++] = nums[cur2++];
            }
            else
            {
                ret += right - cur2 + 1;
                tmp[i++] = nums[cur1++];
            }
        }

        while (cur1 <= mid) tmp[i++] = nums[cur1++];
        while (cur2 <= right) tmp[i++] = nums[cur2++];

        for (int k = left; k <= right; k++)
        {
            nums[k] = tmp[k - left];
        }
        return ret;
    }
};